package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.ReceivingAddress;
import com.example.demo.model.UserInfo;
import com.example.demo.service.ReceivingAddressService;
import com.example.demo.util.ConstVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class ReceivingAddressController {
    
    @Autowired
    private ReceivingAddressService addressService;
    
    @PostMapping("/save-address")
    public AjaxResult saveAddress(@RequestBody ReceivingAddress address, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "用户未登录");
        }
        
        address.setUserId(userInfo.getId());
        if (addressService.addAddress(address)) {
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.fail("添加失败");
    }
    
    @GetMapping("/get-addresses")
    public AjaxResult getAddresses(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "用户未登录");
        }
        
        List<ReceivingAddress> addresses = addressService.getUserAddresses(userInfo.getId());
        return AjaxResult.success(addresses);
    }
    
    @PostMapping("/update-address")
    public AjaxResult updateAddress(@RequestBody ReceivingAddress address, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "用户未登录");
        }
        
        address.setUserId(userInfo.getId());
        if (addressService.updateAddress(address)) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.fail("更新失败");
    }
    
    @PostMapping("/delete-address/{id}")
    public AjaxResult deleteAddress(@PathVariable Integer id, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "用户未登录");
        }
        
        if (addressService.deleteAddress(id)) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.fail("删除失败");
    }
} 